﻿#include <stdio.h>
#include <iostream>
#include <sstream>
#include <curl/curl.h>
using namespace std;
/* ---测试通过---------centos7 gcc curl4.cpp -lstdc++ -o curl4 -lcurl */
size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
	string data((const char*)ptr, (size_t)size * nmemb);

	*((stringstream*)stream) << data << endl;

	return size * nmemb;
}

int main123(int argc, char *argv[])
{

	// 基于当前系统的当前日期/时间
	time_t now = time(0);
	char* dt = ctime(&now);
	cout << dt << "-------------------------------------" << endl;

	/*HTTP GET json data*/
	std::stringstream out;
	CURL* curl = curl_easy_init();
	// 设置URL
	curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:9091/hfdrcall/test/http");
	// 设置接收数据的处理函数和存放变量
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
	// set http method
	curl_easy_setopt(curl, CURLOPT_POST, 1);

	// set header
	struct curl_slist * slist = nullptr;
	slist = curl_slist_append(slist, "Content-Type:application/json;charset=UTF-8");
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"age\" : 123, \"name\" : \"weng\",\"name2\" : \"温文声\"}");
	// 执行HTTP GET操作
	CURLcode res = curl_easy_perform(curl);
	if (res != CURLE_OK) {
		fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
	}

	// 接受数据存放在out中，输出之
	//cout << out.str() << endl;
	string str_json = out.str();


	printf("%s", str_json.c_str());
	curl_easy_cleanup(curl);
	curl_slist_free_all(slist);
	return 0;
}